package com.wanmait.demo.util;

import org.springframework.util.StringUtils;

import java.beans.PropertyEditorSupport;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class TimestampEditor extends PropertyEditorSupport {

	private DateFormat dateFormat;


	public TimestampEditor(String pattern) {
		dateFormat = new SimpleDateFormat(pattern);
	}
	public TimestampEditor() {
		dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	}	

	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		if (!StringUtils.hasText(text)) {			
			setValue(null);
		}		
		else {
			try {
				setValue(new Timestamp(this.dateFormat.parse(text).getTime()));
			}
			catch (ParseException ex) {
				throw new IllegalArgumentException("日期格式不正确: " + ex.getMessage(), ex);
			}
		}
	}

	@Override
	public String getAsText() {
		Timestamp value = (Timestamp) getValue();
		return (value != null ? this.dateFormat.format(value) : "");
	}

}

